import { createRouter, createWebHistory } from 'vue-router'
import Layout from '@/LayOut/index.vue';
import { isLogin, getRole } from '@/utils/user';
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'LayOut',
      meta: {
        roles: '*'
      },
      children: [
        {
          path: '/',
          redirect: '/dashBoard'
        },
        {
          path: 'dashBoard',
          name: '仪表盘',
          meta: {
            roles: '*'
          },
          component: () => import('@/views/DashBoard/index.vue')
        },
        {
          path: 'itemLists',
          name: '商品列表',
          meta: {
            roles: ['a', 'b']
          },
          component: () => import('@/views/ItemLists/index.vue')
        },
        {
          path: 'itemAdd',
          name: '新增商品',
          meta: {
            roles: ['a', 'b', 'admin']
          },
          component: () => import('@/views/ItemAdd/index.vue')
        },
        {
          path: 'itemEdit',
          name: '修改商品',
          meta: {
            roles: ['a', 'b', 'admin']
          },
          component: () => import('@/views/ItemEdit/index.vue')
        },
        {
          path: 'cateLists',
          name: '商品分类列表',
          meta: {
            roles: ['a', 'b', 'admin']
          },
          component: () => import('@/views/CateLists/index.vue')
        },
        {
          path: 'userInfo',
          name: '个人中心',
          meta: {
            roles: ['a', 'b', 'admin']
          },
          component: () => import('@/views/UserInfo/index.vue')
        },
        {
          path: 'orderLists',
          name: '订单列表',
          meta: {
            roles: ['a', 'b']
          },
          component: () => import('@/views/OrderLists/index.vue')
        }
      ],
      component: Layout
    },
    {
      path: '/login',
      name: '登录',
      meta: {
        roles: '*'
      },
      component: () => import('@/views/LoginPage/index.vue')
    },
    {
      path: '/:pathMatch(.*)*',
      name: '404',
      meta: {
        roles: '*'
      },
      component: () => import('@/views/NotFound/index.vue')
    },
    {
      path: '/noauth',
      name: 'noauth',
      meta: {
        roles: '*'
      },
      component: () => import('@/views/NoAuth/index.vue')
    },
  ]
})
router.beforeEach((to) => {
  if (to.path!== '/login' &&!isLogin()) {
    return {
      path: '/login',
      query: {
        redirect: to.path
      }
    }
  }
  if (to.path === '/login' && isLogin()) {
    return '/dashBoard'
  }
  if (to.path!== '/login' &&isLogin()) {
    // 不是去登录页 且登录了
    const role = getRole() as string;
    const roles = to.meta.roles as string[]|string;
    if (roles !== '*' && !roles.includes(role)) {
      return '/noauth'
    }
  }

})
export default router
